<template>
  <div class="Voice">
    <span
      @mousedown="Start"
      @mouseup="End"
      class="iconfont icon-huatong attachment"
    ></span>
    <video ref="localVideo" style="display: none" autoplay playsinline></video>
  </div>
</template>
<script>
import BenzAMRRecorder from "benz-amr-recorder";
import { isWebRTC, getUserMedia, StartRecord, GetMediaBlob } from "./WebRTC";
import Uploader from "packages/BaseUpload/uploader";
import FileMixin from './FileMixin.js';
export default {
  name: "Voice",
    mixins: [FileMixin],
  data() {
    return {
      Stream: null,
      mediaRecorder: null,
      TimeOut: null,
      StartTime: 0,
    };
  },
  methods: {
    // 开始录制，分环境
    Start() {
      if (this.ua === "wx") {
        // 微信
      } else if (this.ua === "dd") {
        // 钉钉
      } else if (this.ua === "Other") {
        // 其他浏览器
        this.StartTermination();
      }
    },
    End() {
      if (this.ua === "wx") {
        // 微信
      } else if (this.ua === "dd") {
        // 钉钉
      } else if (this.ua === "Other") {
        // 其他浏览器
        this.EndTermination();
      }
    },
    // 初始化WebRTC
    StartTermination() {
      if (!isWebRTC) {
        alert(this.$t('im.imChat.components.messageBox.voice.tips1'));
      }
      // 初始化WebRTC，录制音频
      getUserMedia({
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true,
        },
      }).then((mediaStream) => {
        this.Stream = mediaStream;
        this.$refs.localVideo.srcObject = this.Stream;
        console.log("初始化完成");
        StartRecord(this.Stream, "audio/webm;")
          .then((media) => {
            console.log("开始录制");
            this.mediaRecorder = media;
            this.StartTime = Date.now();
            //最多录制60s语音，到时自动关闭
            this.TimeOut = setTimeout(() => {
              this.EndTermination();
              clearTimeout(this.TimeOut);
              this.StartTime = 0;
            }, 6000);
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },
    // 录制完成
    EndTermination() {
      if (!this.mediaRecorder) return;
      // 小于500ms的语音不录制
      if (Date.now() - this.StartTime < 500) return;
      this.mediaRecorder.stop();
      // 关闭当前RTC
      this.$refs.localVideo.srcObject = null;
      this.Stream = null;
      this.mediaRecorder = null;

      let MediaBlob = GetMediaBlob();
      console.log("结束录制");

      // 适配企业微信语音发送，转换为amr格式文件
      let amr = new BenzAMRRecorder();
      amr.initWithBlob(new Blob(MediaBlob)).then(() => {
        // 转换为 file 格式上传
        let MediaFile = new window.File([amr.getBlob()], `${Date.now()}.amr`, {
          type: "",
        });
        this.Upload(MediaFile);
      });
    },
    async Upload(file) {
      try {
        const { data } = await Uploader.upload(file, "/files/upload");
        this.$emit("UploadData", data);
      } catch (error) {}
    },
  },
  computed: {
    ua() {
      const ua = navigator.userAgent.toLowerCase();
      if (
        ua.match(/MicroMessenger/i) == "micromessenger" ||
        ua.match(/WeiBo/i) == "weibo"
      ) {
        //微信和微博环境
        return "wx";
      } else if (ua.indexOf("dingtalk") >= 0) {
        //钉钉环境
        return "dd";
      } else {
        //其他浏览器环境
        return "Other";
      }
    },
  },
};
</script>
<style scoped>
.attachment {
  color: #8c8c8c;
  cursor: pointer;
}
.attachment:hover {
  color: $color-primary;
}
.Voice {
  display: inline-block;
}
</style>
